import React from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Card, Row, Col, Badge, Drawer, Modal,
  Button, Avatar, Skeleton,
  List, Tag, Typography, Divider, Space
} from 'antd';
import {
  PlusOutlined,
  MenuOutlined,
} from '@ant-design/icons';
import styles from './Welcome.less';
import Clusteredstacked from './components/Clusteredstacked'
import Withline from './components/Withline'
import ModelConfig from './components/ModelConfig'
import EcChartExp from './components/EcChart'
import Stacked from './components/Stacked'
import { Link, connect } from 'umi';
import imgReport from '../assets/report.png'
import imgAvatar from '../assets/avatar.png'
import moment from 'moment'
import UploadUtil from './UploadUtil'

const { Meta } = Card;
const { Title, Paragraph, Text } = Typography;
const PageHeaderContent = ({ currentUser }) => {
  const loading = currentUser && Object.keys(currentUser).length;
  if (!loading) {
    return <Skeleton avatar paragraph={{ rows: 1 }} active />;
  }
  return (
    <div>
      <Avatar size="large" src={currentUser.avater ? UploadUtil.imgServ + currentUser.avater : imgAvatar} />
      <span className={styles.welcomtxt}>你好，{currentUser.userName}，祝你开心每一天！{currentUser.emailAddress}</span>
    </div>
  );
};
class Welcome extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      visible: false,
      visibleApp: false,
      visibleCon: false,
      appURL: "",
      appTitle: 'App',
      modlist: [],
      userlist: [],
      contentlist: [],
      article: {},
      userModules: [],
      checkedList: [],
    }
  }
  componentDidMount() {
    this.fetchModuls();
    this.fetchUsers();
    //this.fetchAnnounce();
    this.fetchUserModules();
    this.props.dispatch({
      type: 'Department/getAll',
    });
  }
  fetchModuls = () => {
    this.props.dispatch({
      type: "CrudModel/getAll",
      payload: { SkipCount: 0, MaxResultCount: 1000 },
      control: 'Module',
    }).then(() => {
      var resp = this.props.response.result;
      if (resp) {
        var modlist = resp.items;
        this.setState({ loading: false, modlist });
      }
    });
  }
  fetchUserModules = () => {
    this.props.dispatch({
      type: "UserModule/getUserModule",
    }).then(() => {
      var resp = this.props.UserModule.response;
      if (resp && resp.result) {
        var userModules = resp.result;
        var checkedList = [];
        userModules.forEach(item => {
          checkedList.push(item.moduleId);
        });
        this.setState({ loading: false, userModules, checkedList });
      }
    });
  }
  fetchUsers = () => {
    this.setState({ loading: true });
    this.props.dispatch({
      type: "CrudModel/getAll",
      payload: { SkipCount: 0, MaxResultCount: 10 },
      control: 'User',
    }).then(() => {
      var resp = this.props.response.result;
      if (resp) {
        var userlist = resp.items;
        this.setState({ loading: false, userlist });
      }
    });
  }
  fetchAnnounce = () => {
    this.setState({ loading: true });
    this.props.dispatch({
      type: "CrudModel/getAll",
      payload: { SkipCount: 0, MaxResultCount: 8 },
      control: 'Article',
    }).then(() => {
      var resp = this.props.response.result;
      if (resp) {
        var contentlist = resp.items;
        this.setState({ loading: false, contentlist });
      }
    });
  }
  switchDrawer = (val) => {
    this.setState({
      visible: val,
    });
  };
  switchModal = (val) => {
    this.setState({
      visibleApp: val
    });
  };
  switchModalCon = (val) => {
    this.setState({
      visibleCon: val
    });
  };
  openModal = (app) => {
    if (app.moduleType == "CS") {
      //window.open(app.protocol + "://open");
      window.location.href = app.protocol + "://open";
    }
    else {
      this.setState({
        visibleApp: true,
        appTitle: app.moduleName,
        appURL: app.modulePath,
      });
    }

  };
  closeDraw = () => {
    this.switchDrawer(false);
    this.fetchUserModules();
  }
  deptCvt = (dptid) => {
    var obj = this.props.deptlist.filter(i => i.id == dptid)[0];
    if (obj)
      return obj.deptName;
    else
      return dptid
  }
  getArticle = (id) => {
    const { dispatch } = this.props;
    if (id > 0) {
      dispatch({
        type: 'CrudModel/get',
        payload: { id },
        control: 'Article',
      }).then(() => {
        var result = this.props.response.result;
        if (result) {
          result.contents = decodeURI(result.contents);
          this.setState({ article: result });
          this.switchModalCon(true);
        }
      });
    }
  }
  render() {
    const { currentUser } = this.props;
    const { article, userModules } = this.state;
    return (
      <PageHeaderWrapper title={false}
        content={<PageHeaderContent currentUser={currentUser} />}
      >
        <Row gutter={[12, 12]} align="middle" >
          {
            userModules.map((item, key) => (
              <Col key={key} xs={24} sm={12} md={3} lg={6} xl={6} xxl={3}>
                <Card hoverable={true} className={styles.mod} onClick={() => this.openModal(item)}>
                  <Badge count={item.num}>
                    <img style={{ width: 48, height: 48, marginBottom: 12 }} src={item.logo ? UploadUtil.imgServ + item.logo : imgReport} />
                  </Badge>
                  <Meta title={item.displayName} />
                </Card>
              </Col>
            ))
          }
          <Col key={9999} xs={24} sm={12} md={3} lg={6} xl={6} xxl={3}>
            <Card hoverable={true} className={styles.mod}>
              <a onClick={() => this.switchDrawer(true)}>
                <PlusOutlined className={styles.ico} />
              </a>
              <Meta title="添加应用" />
            </Card>
          </Col>
        </Row>
        <Row gutter={[12, 12]}>
          <Col span={16}>
              <Card title={<b>产能监控</b>}><Stacked /></Card>
              <Card title={<b>部门业绩</b>}
                extra={[<Button key="B1" type="link" icon={<MenuOutlined />} />]}>
                <Clusteredstacked />
              </Card>
              <Card
                title="通讯录"
                loading={this.state.loading}
                extra={<Link to="/ContactBook">全部</Link>}
              >
                {this.state.userlist.map((item) => (
                  <Card.Grid key={item.id}>
                    <Meta
                      avatar={<Avatar src={item.avater ? UploadUtil.imgServ + item.avater : imgAvatar} />}
                      title={item.fullName + "，工号：" + item.empID}
                      description={<a href={"mailto://" + item.emailAddress}>{item.emailAddress}</a>}
                    />
                    <div className={styles.ptxt}>电话：{item.telphone}，{this.deptCvt(item.deptID)}</div>
                  </Card.Grid>
                ))}
              </Card>
            
          </Col>
          <Col span={8}>
              <Card title={<b>人员配置</b>}
                extra={[<Button key="B1" type="link" icon={<MenuOutlined />} />]}>
                <Withline />
              </Card>
          </Col>
          {/* <Col span={8}>
            <Card title="通知公告">
              <List
                dataSource={this.state.contentlist}
                renderItem={(item, key) => (
                  <List.Item>
                    {key + 1}. <a onClick={() => this.getArticle(item.id)}>{item.title}。 </a>
                    <Tag color="lime">{moment(item.creationTime).format('YYYY-MM-DD')}</Tag>
                  </List.Item>
                )}
              />
            </Card>

          </Col> */}
        </Row>
        <Drawer
          title={<b>应用设置</b>}
          placement="right"
          closable={false}
          onClose={() => this.switchDrawer(false)}
          visible={this.state.visible}
          destroyOnClose={true}
        >
          <ModelConfig modelList={this.state.modlist} checkedList={this.state.checkedList} closeDraw={(para) => this.closeDraw(para)} />
        </Drawer>
        <Modal
          title={<b>{this.state.appTitle}</b>}
          width="100%"
          style={{ top: "0px" }}
          maskClosable={false}
          visible={this.state.visibleApp}
          onOk={() => this.switchModal(false)}
          onCancel={() => this.switchModal(false)}
          footer={null}>
          <iframe
            className={styles.iframe}
            src={this.state.appURL} />
        </Modal>
        <Modal
          title={<b>公告详情</b>}
          width="50%"
          visible={this.state.visibleCon}
          onOk={() => this.switchModalCon(false)}
          onCancel={() => this.switchModalCon(false)}
          footer={null}
          destroyOnClose={true}>
          <div>
            <Title level={3}>{article.title}</Title>
            <Divider />
            <Paragraph><div dangerouslySetInnerHTML={{ __html: article.contents }} /></Paragraph>
            <Divider />
            <Paragraph>{moment(article.creationTime).format('YYYY-MM-DD HH:MM:SS')} 发布
            <Divider type="vertical" />
              {moment(article.lastModificationTime).fromNow()} 修改</Paragraph>
          </div>
        </Modal>
      </PageHeaderWrapper>
    )
  }
}
export default connect(({ user, CrudModel, Module, Department, Article, UserModule }) => ({
  currentUser: user.currentUser,
  response: CrudModel.response,
  current: Module.current,
  deptlist: Department.deptlist,
  Article,
  UserModule,
}))(Welcome);